<script>
import {uploadFile} from "../../../static/utils/uploadImg";
import {getAddressByLonLatApi} from "../../../api/common/location";
import store from "../../../store";
export default {
  name: "index",
  emit: ['change', 'input', 'delete'],
  props: {
    value: {
      type: [String, Object],
      default: '',
    },
    url: {
      type: String,
      default: 'common/upload',
    },
    accept: {
      type: String,
      default: 'image',
    },
    capture: {
      type: [String, Array],
      default: ['album', 'camera'],
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    desc: {
      type: String,
      default: '上传图片',
    },
    maxCount: {
      type: Number,
      default: 1,
    },
    showCount: {
      type: Boolean,
      default: true,
    },
    isBreak: {
      type: Boolean,
      default: true,
    },
    waterMark: {
      type: Boolean,
      default: true,
    },
    tenantName: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      list: [],
      canvasWidth: 150,
      canvasHeight: 150,
      showCanvas: false,
      canvasId: 'canvasId', // `a_${(Math.random()+"").replaceAll('.', '')}`
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          this.list = [{
            url: val,
            status: 'success',
            message: '上传成功'
          }]
        }
      },
      immediate: true
    }
  },
  methods: {
    formatDate(date) {
      console.log('获取日期开始')
      var yyyy = date.getFullYear();
      var mm = date.getMonth() < 9 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1); // getMonth() is zero-based
      var dd  = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hh = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      var min = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      console.log('获取日期结束')
      return yyyy + "-" + mm + "-" + dd + " " + hh + ":" + min + ":" + ss;
    },
    // addWaterMark(tempFilePath,pictureDate,lonlat,address,tenantName, name){
    //   return new Promise((resolve,reject)=>{
    //     console.log(456)
    //     wx.createSelectorQuery()
    //         .select('#myCanvas') // 在 WXML 中填入的 id
    //         .fields({ node: true, size: true })
    //         .exec((res) => {
    //           // Canvas 对象
    //           const canvas = res[0].node
    //           // 渲染上下文
    //           const ctx = canvas.getContext('2d')
    //           console.log(ctx)
    //         })
    //   })
    // },
// 给图片加水印
    //添加拍摄水印
    //pictureDate：拍照日期,lonlat：拍摄经纬度,address：拍摄地点,
    addWaterMark(tempFilePath,pictureDate,lonlat,address,tenantName, name){
      console.log('添加水印开始')
      let e=this;
      this.showCanvas = true;
      return new Promise((resolve,reject)=>{
        uni.showLoading({
          title: '图片加载中',
        })
        console.log('获取图片信息开始')
        uni.getImageInfo({
          // 注意此时的地址是正常的图片地址 以下是给图片添加水印返回新的url地址
          src: tempFilePath,
          success: function(res) {

            console.log('获取图片信息成功')
            // 得到图片宽高
            let {width,height} = res;
            // 定义画布大小
            e.canvasWidth = width;
            e.canvasHeight = height;

            console.log(e.canvasWidth, 321)
            // 在自定义组件内 需要传递第二参数 this canvas才生效
            var ctx = uni.createCanvasContext(e.canvasId, e);
            console.log('开始构建图像内容')
            // 清除画布内像素
            ctx.clearRect(0, 0, width, height);
            // 开始一条路径
            ctx.beginPath();
            ctx.fillStyle = '#000000'; //将线条颜色设置为白色
            ctx.fillRect(0, 0, width, height);
            // 在画布上绘制图像
            ctx.drawImage(tempFilePath, 0, 0, width, height);
            // 为图片添加水印
            let unit= ((width/height)>(375/812))?(1/375)*width:(1/812)*height;//1px对应图片上的单位
            e.drawRadiusRect(ctx,0,height - 92*unit,width,92*unit,'',0,'rgba(0,0,0,0.3)',unit)
            let fontSize=10*unit;//375px对应10px字号
            ctx.setFontSize(fontSize);
            ctx.setFillStyle('rgba(0,0,0,1)');
            let x=12*unit;
            //日期
            ctx.setFillStyle('rgba(225,225,225,1)');
            ctx.fillText(pictureDate,x,height-70*unit);
            //地址
            ctx.fillText(address,x,height-52*unit);
            //经纬度
            ctx.fillText(lonlat,x,height-33*unit);
            // 业务员
            ctx.fillText(name,x,height-14*unit);

            let y=height - 32*unit;
            let width0=fontSize*name.length+12*unit;
            let height0=20*unit;
            let radius=2*unit;//圆角
            let rectBg='rgba(0,0,0,0)';
            // 业务员
            ctx.fillText(name,x,height-14*unit);
            // e.drawRadiusRect(ctx,x,y,width0,height0,name,radius,rectBg,unit)
            //方位
            let x1=x+width0+6*unit;
            // let width1=fontSize*tenantName.length+12*unit;
            // let w=tenantName.length==1?width1: 57*unit;
            // e.drawRadiusRect(ctx,x1,y,w,height0,tenantName,radius,rectBg,unit)
            // 业务员
            if (tenantName) {
              ctx.fillText(`业主姓名：${tenantName}`,x1,height-14*unit);
            }
            console.log('开始绘制图像内容到画布')
            // 开始绘制添加水印的图片并显示在页面中
            ctx.draw(false, () => {
              console.log('绘制成功')
              setTimeout(() => {
                console.log('画布内容转url')
                uni.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  width: width,
                  height: height,
                  destWidth: width,
                  destHeight: height,
                  quality: 1,
                  fileType: 'jpg',
                  canvasId: e.canvasId,
                  success: function(resb) {
                    console.log('画布内容转url成功')
                    uni.hideLoading();
                    e.canvasWidth = width;
                    e.canvasHeight = height;
                    e.isShow = false;
                    resolve(resb.tempFilePath)
                    console.log('绘制成功，得到图像路径', resb.tempFilePath)
                    e.showCanvas = false;
                  },
                  fail(err) {
                    console.log('画布内容转url失败', err)
                    console.log(err)
                    uni.hideLoading()
                    e.canvasWidth = 0;
                    e.canvasHeight = 0;
                    e.isShow = false;
                    console.log('绘制失败，失败信息：', err)
                    // e.$utils.showNoneToast('水印绘制失败，请重新拍摄');
                    uni.showToast({
                      title: '水印绘制失败，请重新拍摄',
                      icon: 'none'
                    })
                    reject();
                  }
                }, e)
              }, 500);
            }, e);

            // uni.canvasToTempFilePath({
            //   x: 0,
            //   y: 0,
            //   width: width,
            //   height: height,
            //   destWidth: width,
            //   destHeight: height,
            //   quality: 1,
            //   fileType: 'jpg',
            //   canvasId: e.canvasId,
            //   success: function(resb) {
            //     console.log('画布内容转url成功')
            //     uni.hideLoading();
            //     e.canvasWidth = width;
            //     e.canvasHeight = height;
            //     e.isShow = false;
            //     resolve(resb.tempFilePath)
            //     console.log('绘制成功，得到图像路径', resb.tempFilePath)
            //   },
            //   fail(err) {
            //     console.log('画布内容转url失败', err)
            //     console.log(err)
            //     uni.hideLoading()
            //     e.canvasWidth = 0;
            //     e.canvasHeight = 0;
            //     e.isShow = false;
            //     console.log('绘制失败，失败信息：', err)
            //     // e.$utils.showNoneToast('水印绘制失败，请重新拍摄');
            //     uni.showToast({
            //       title: '水印绘制失败，请重新拍摄',
            //       icon: 'none'
            //     })
            //     reject();
            //   }
            // }, e)
          },
          fail: function(err) {
            console.log(err.errMsg);
            uni.hideLoading()
            uni.showToast({
              title: '该图片为矢量图不支持下载',
              icon: 'none'
            })
            // e.$utils.showNoneToast('该图片为矢量图不支持下载');
          }
        })
      })
    },
    //画带圆角的长方形
    drawRadiusRect(ctx,x,y,w,h,name,r ,rectBg,unit){
      // 绘制圆角矩形
      ctx.beginPath();
      ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
      ctx.moveTo(x + r, y);
      ctx.lineTo(x + w - r, y);
      ctx.lineTo(x + w, y + r);

      ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
      ctx.lineTo(x + w, y + h - r);
      ctx.lineTo(x + w - r, y + h);

      ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
      ctx.lineTo(x + r, y + h);
      ctx.lineTo(x, y + h - r);

      ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
      ctx.lineTo(x, y + r);
      ctx.lineTo(x + r, y);
      //使用arcTo在安卓上有一个边会呈现锯齿形
      // ctx.moveTo(x + cornerRadius, y);      // 左上角直线开始
      // ctx.lineTo(x + width - cornerRadius, y);  // 到右上角圆弧开始点
      // ctx.arcTo(x + width, y, x + width, y + cornerRadius, cornerRadius);  // 右上角圆弧
      // ctx.lineTo(x + width, y + height - cornerRadius);  // 右侧直线
      // ctx.arcTo(x + width, y + height, x + width - cornerRadius, y + height, cornerRadius);  // 右下角圆弧
      // ctx.lineTo(x + cornerRadius, y + height);  // 底部直线
      // ctx.arcTo(x, y + height, x, y + height - cornerRadius, cornerRadius);  // 左下角圆弧
      // ctx.lineTo(x, y + cornerRadius);  // 左侧直线
      // ctx.arcTo(x, y, x + cornerRadius, y, cornerRadius);  // 左上角圆弧结束，连接到开始点
      // ctx.closePath();  // 关闭路径，连接开始点和结束点

      // 设置样式并填充圆角矩形
      ctx.fillStyle = rectBg;
      ctx.fill();
      //填上内容
      ctx.beginPath();
      ctx.setFillStyle('rgba(225,225,225,1)');
      ctx.fillText(name,x+6*unit,y+13*unit);
    },
    //获取设备方向的字符串，传入角度，返回 N、S、W、E、N?E、N?W、S?E、S?W
    getDirection(angel){
      console.log(270.00==270)
      let str='';
      if(angel==0){
        str='N';
      }else if(angel==90){
        str='E'
      }else if(angel==180){
        str='S'
      }else if(angel==270){
        str='W'
      }else if(angel>0&&angel<90){
        str=`N${Number(angel).toFixed(2)}°E`
      }else if(angel>90&&angel<180){
        str=`S${(180-Number(angel)).toFixed(2)}°E`
      }else if(angel>180&&angel<270){
        str=`S${(Number(angel)-180).toFixed(2)}°W`
      }else if(angel>270&&angel<360){
        str=`N${(360-Number(angel)).toFixed(2)}°W`
      }
      return str;
    },

    // 公共图片上传
    async uploadImg(event, key) {
      const res = await uni.getLocation({
        type: 'wgs84',
        geocode: true,
      })
      let long = null;
      let lat = null;
      let address = null;
      let name = null;
      if (res[1] && res[1].longitude && res[1].latitude) {
        long = res[1].longitude;
        lat = res[1].latitude;
        const resp = await getAddressByLonLatApi(`${long},${lat}`)
        address = resp.data;
      }
      const file = event.file;
      this.list.push({
        ...file,
        status: 'uploading',
        message: '上传中'
      })
      this.userInfo = await store.dispatch("user/getInfo")
      try {
        name = this.userInfo.user.loginName;
      } catch (e) {
        console.log(e)
      }
      console.log(this.userInfo, 789789)
      console.log(file.url, '开始上传')
      // const canvasFileUrl = await this.addWaterMark(file.url,'2021-01-01 12:00:00','116.123456,39.123456','北京市朝阳区','90')
      // console.log(canvasFileUrl, 1999)
      // uploadFile(this.$props.url, { url: canvasFileUrl }).then( res => {
      let fileUrl = '';
      if (this.$props.waterMark) {
        fileUrl = await this.addWaterMark(
            file.url,
            `时间：${this.formatDate(new Date())}`,
            `坐标：${long || '-'},${lat || '-'}`,
            `地址：${address || '暂无'}`,
            this.$props.tenantName,
            `踏勘人员: ${name}`
        )
      } else {
        fileUrl = file.url;
      }
      uploadFile(this.$props.url, { url: fileUrl }).then( res => {
        console.log('上传成功')
        let data = JSON.parse(res.data);
        data = data.data || data;
        this.list.splice(0, 1, Object.assign(this.list[0], {
          status: 'success',
          message: '上传成功',
          url: data.fullPath
        }))
        this.$emit('input', data.fullPath)
        this.$emit('change', data.fullPath, data);
      })
    },
    deleteImg(name) {
      this.list = []
      this.$emit('delete', name)
      this.$emit('input', '')
      // this.$emit('change', data.fullPath, data);
    },
  },
}
</script>

<template>
<!--  :style="`width: ${canvasWidth}px;height: ${canvasHeight}px`"-->
  <view class="img-upload">
    <view class="canvas-wrap">
      <canvas
          v-if="showCanvas"
          class="canvas"
          :key="canvasId"
          canvas-id="canvasId"
          :style="{width:`${canvasWidth}px`, height: `${canvasHeight}px`}"
          id="canvasId"
      ></canvas>
    </view>
    <u-upload
        :fileList="list"
        name="1"
        :maxCount="1"
        :accept="accept"
        width="75"
        height="75"
        @afterRead="(event) => { uploadImg(event, 'roofPhotoOne') }"
        @delete="deleteImg('roofPhotoOne')"
        :disabled="disabled"
        :deletable="!disabled"
        :capture="capture"
    >
      <!--slot-->
      <slot>
        <view class="upload-cover">
          <view class="icon-wrap">
            <u-icon class="upload-cover__icon" name="camera-fill" size="30" color="#bbb"></u-icon>
          </view>
          <view>
            <view class="desc" :style="{display: isBreak ? 'block' : 'inline'}">{{disabled ? '未上传' : desc}}</view>
            <view
                class="max-count"
                v-if="showCount"
                :style="{display: isBreak ? 'block' : 'inline', marginTop: isBreak ? '2px' : '0px'}"
            >({{maxCount}}张)</view>
          </view>
        </view>
      </slot>
    </u-upload>
    <view class="img-title" v-if="desc !== '上传图片' && disabled">{{desc === '上传图片' ? '' : desc}}</view>
  </view>
</template>

<style scoped lang="scss">
.img-upload{
  display: inline-block;
  margin: 0px 8px 8px 0;
  vertical-align: top;
}
.upload-cover{
  position: relative;
  width: 75px;
  height: 75px;
  max-width: 75px;
  display: inline-block !important;
  text-align: center;
  padding: 0px;
  background: #f5f5f5;
  border: 1px dashed #ddd;
  &__icon{
    //position: relative;
    //top: 50%;
    //left: 50%;
    //transform: translate(-50%, -50%);
    display: inline-block;
  }
  .icon-wrap{
    text-align: center;
    display: inline-block;
    padding-top: 10px;
  }
  .desc{
    font-size: 12px;
    text-align: center;
    color: #bbb;
    display: inline-block;
    line-height: 12px;
  }
  .max-count{
    font-size: 10px;
    color: #bbb;
    line-height: 12px;
  }
}
.img-title{
  text-align: center;
  color: #888;
  padding-right: 8px;
}
/deep/ .u-icon--right{
  flex-direction: column;
}
</style>
<style lang="scss">
.u-upload__wrap__preview{
  margin: 0;
}
.canvas-wrap{
  width: 10px;
  height: 10px;
  //overflow: hidden;
  position: relative;
  opacity: 100;
  .canvas{
    position: absolute;
    left: -9999px;
    top: -9999px;
  }
}
</style>
